﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace VideoControl
{
    public partial class RecordPlay : UserControl
    {
        public RecordPlay()
        {
            InitializeComponent();
        }
        private bool isOpened = false;

        public bool IsOpened
        {
            get { return isOpened; }
        }
        private bool isPlaying = false;

        public bool IsPlaying
        {
            get { return isPlaying; }
        }

    //    int fast_cnt = 0;
    //    int slow_cnt = 0;
        private int nPort = -1;
        private void FileRefDone(int nPort, ushort nUser)
        {
            ushort nSize = 0;
           HCSDK.HikPlayer.PlayM4_GetRefValue(0, IntPtr.Zero, ref nSize);
            byte[] Datas = new byte[nSize];

            GCHandle hObject = GCHandle.Alloc(Datas, GCHandleType.Pinned);
            IntPtr pObject = hObject.AddrOfPinnedObject();

            HCSDK.HikPlayer.PlayM4_GetRefValue(0, pObject, ref nSize);

           HCSDK.HikPlayer.PlayM4_SetRefValue(0, pObject, nSize);

            if (hObject.IsAllocated) hObject.Free();
        }
        /// <summary>
        /// 播放录像文件
        /// </summary>
        /// <param name="FileName">将要播放文件的录像名</param>
        public  void Play(string FileName)
        {
            if (!isOpened)
            {

                
                    if (!HCSDK.HikPlayer.PlayM4_GetPort(ref nPort))  
                        throw new Exception(); 
                    if (!HCSDK.HikPlayer.PlayM4_SetFileRefCallBack(nPort, FileRefDone, 0))
                         throw new Exception(); 
                    if (!HCSDK.HikPlayer.PlayM4_SetFileEndMsg(nPort, this.Handle, 0x1111))
                        throw new Exception(); 
                    if (!(isOpened = HCSDK.HikPlayer.PlayM4_OpenFile(nPort, FileName)))
                        throw new Exception(); 
               
            }
           // else throw new InvalidOperationException();
            if (isOpened && !isPlaying)
                isPlaying = HCSDK.HikPlayer.PlayM4_Play(nPort, this.Handle);
        }

        public void Stop()
        {
            if (this.isPlaying)
            {
                
        
            if (!HCSDK.HikPlayer.PlayM4_Stop(nPort)) 
                throw new Exception(); 
            if (!HCSDK.HikPlayer.PlayM4_CloseFile(nPort))
                throw new Exception(); 
            if (!HCSDK.HikPlayer.PlayM4_FreePort(nPort))
                throw new Exception(); 
               
               
                this.isPlaying = false;
                this.isOpened = false;
                this.Invalidate();
            }
        }

    }
}
